package root.electronclass.electronclass.other

import android.app.Activity
import android.util.Log
import android.view.View
import androidx.core.view.isVisible
import androidx.lifecycle.coroutineScope
import root.electronclass.electronclass.common.base.ViewBindingActivity
import root.electronclass.electronclass.common.util.KRReadThreadUtil
import root.electronclass.electronclass.common.util.TextUtils
import root.electronclass.electronclass.R
import root.electronclass.electronclass.databinding.ActivityCardBinding
import root.electronclass.electronclass.ext.CoroutineExceptionHandler
import root.electronclass.electronclass.setup
import root.electronclass.electronclass.mvp.GlobalParameter
import root.electronclass.electronclass.mvp.base.BaseResponse
import root.electronclass.electronclass.mvp.base.CallbackNext
import root.electronclass.electronclass.mvp.entity.EcardAttnDTO
import root.electronclass.electronclass.mvp.rest.RestManager
import com.hikvision.dmb.SwingCardCallback
import com.hikvision.dmb.util.InfoUtilApi
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import retrofit2.Call


/**
 * 刷卡认证
 */
class CardActivity : ViewBindingActivity<ActivityCardBinding>() {
    private val krReadThreadUtil = KRReadThreadUtil()
    override fun init() {
        binding.top.setup(lifecycle, "")
        binding.top.title.visibility = View.GONE
        binding.back.back.setOnClickListener {
            finish()
        }
        if (GlobalParameter.getEcardInfo().type == 5){
            karCard()
        }else {
            InfoUtilApi.swingCard(swingCardCallback)
        }


        //设备id 改成333可以用这三种身份登录
//                swingCardCallback.getInfo("A:202504200002")//普通学生
//                swingCardCallback.getInfo("A:3460162238")//班干部
//                swingCardCallback.getInfo("A:202404200001")//老师
    }

    private fun karCard() {
        krReadThreadUtil.startReadThread { _: Int, cardNum: String? -> sendCardNumber(cardNum) }
    }

    private fun sendCardNumber(card: String?) {
        val cardNum = TextUtils.addZeroForNum(card, 10)
        runOnUiThread {
            binding.cardNum.text = cardNum
        }

        if (cardNum == "" || cardNum.isEmpty()) {
            return
        }
        RestManager.getInstance().initRest().cardNo(cardNum).enqueue(object : CallbackNext<BaseResponse<String>>(mDialogViewModel) {
            override fun onSuccessful(call: Call<BaseResponse<String>>?, response: BaseResponse<String>) {
                if (response.isSuccess) {
                    RestManager.getInstance().token = response.rows
                    RestManager.getInstance().initService()
                    GlobalParameter.setEventType(1)
                    GlobalParameter.setCardNum(cardNum) //考勤打卡
                    if (intent.getIntExtra("RequestCode", 0) == AttestationActivity.ATTENDANCE) {
                        RestManager.getInstance().initRest().saveAttn(EcardAttnDTO())
                                .enqueue(object : CallbackNext<BaseResponse<Any>>(mDialogViewModel) {
                                    override fun onSuccessful(call: Call<BaseResponse<Any>>?, response: BaseResponse<Any>?) {
                                        Log.i("CardActivity", "onSuccessful: $response")
                                        binding.resultCl.isVisible = true
                                        if (response?.code == 200) {
                                            binding.resultTv.text = "打卡成功"
                                            binding.result.setImageResource(R.mipmap.success_icon)
                                            binding.resultTv1.text = "恭喜你，已完成考勤打卡"
                                        } else {
                                            binding.resultTv.text = "打卡失败"
                                            binding.result.setImageResource(R.mipmap.fault_icon)
                                            binding.resultTv1.text = response?.msg
                                        }
                                        lifecycle.coroutineScope.launch(CoroutineExceptionHandler()) {
                                            delay(3000)
                                            setResult(Activity.RESULT_OK)
                                            finish()
                                        }
                                    }

                                    override fun onError(call: Call<BaseResponse<Any>>?, response: BaseResponse<Any>?) {
                                        binding.resultTv.text = "打卡失败"
                                        binding.result.setImageResource(R.mipmap.fault_icon)
                                        binding.resultTv1.text = response?.msg
                                        lifecycle.coroutineScope.launch(CoroutineExceptionHandler()) {
                                            delay(3000)
                                            setResult(Activity.RESULT_OK)
                                            finish()
                                        }
                                    }

                                })
                    } else {
                        toast("登录成功")
                        setResult(Activity.RESULT_OK)
                        finish()
                    }
                } else if (response.code == 505) {
                    toast(response.msg)
                }
            }

            override fun onError(call: Call<BaseResponse<String>>?, response: BaseResponse<String>?) {
                toast(response?.msg)
            }

        })

    }

    private var swingCardCallback = object : SwingCardCallback.Stub() {
        override fun getInfo(info: String?) {
            val num: List<String>? = info?.split(":")
            val card = num?.get(1) ?: ""
            sendCardNumber(card)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        if (GlobalParameter.getEcardInfo().type == 5){
            krReadThreadUtil.stopReadThread()
        }else {
            InfoUtilApi.unregisterSwingCard(swingCardCallback)
        }
    }
}